import { SERVICE_NAME } from '@/credit/plugins/constant'
import { getData, addData, updateData } from '@vimi/utils-api'
import {
  calcRole,
  calcStatus,
} from '@/credit/views/county/unionProvince/components/contractApprove/index'
import { dateFormat } from '@/common/utils/common'
import { nzhToMoney, arrayFromString } from '@vimi/utils-tool'
const approvalTableName = 'loan_approval'
const attachTableName = 'datum_customer_attachment'
const relatedTableName = 'customer_related'
const noticeTableName = 'loan_notice'
export const countyCorpEdit = (row, auth = {}, user) => {
  const { userId } = user
  return (
    userId === auth.userId &&
    +row.loanApprovalStatus === 1 &&
    +row.loan_approval_status < 2 &&
    +user.orgRegionLever > 1
  )
}

export const countyResAEdit = (row, user) => {
  const { userId } = user
  return userId === row.res_a && +row.loan_approval_status === 0
}

export const getApprovalNoEdit = (row, auth = {}, user) => {
  return countyResAEdit(row, user) || countyCorpEdit(row, auth, user)
}

export const updateRelatedLoanStatus = (id, status) =>
  updateData(SERVICE_NAME, relatedTableName, id, {
    loan_approval_status: status,
  })

/**
 * 获取项目审批申请表
 * @param {string} relatedId 关联ID
 */
export const getApproval = relatedId =>
  getData(SERVICE_NAME, approvalTableName, {
    customer_related_id: relatedId,
  }).then(res => res?.data?.[0] ?? {})

export const updateApproval = (id, data) => updateData(SERVICE_NAME, approvalTableName, id, data)

export const addApproval = data => addData(SERVICE_NAME, approvalTableName, data)

export const getAttachment = (relatedId, attachName = []) =>
  getData(
    SERVICE_NAME,
    attachTableName,
    {
      'file_type.eq': 1,
      'customer_related_id.eq': relatedId,
      'attachment_type.in': attachName.join(','),
    },
    { create_time: 'asc' }
  ).then(res => {
    const attachment = []
    const data = res?.data ?? []
    data.forEach(item => {
      const images = arrayFromString(item.attachment).map(img => {
        return { url: img, id: item.id, attachment_type: item.attachment_type }
      })
      attachment.push(...images)
    })
    return attachment
  })

export const sendNotice = (related, entrustContract) => {
  const isPerson = related.customer_type === 2
  const data = {
    customer_related_id: related.customer_related_id,
    gua_org_id: related.recommend_service,
    bank_name: related.bank_name,
    entrust_gua_no: entrustContract.entrust_contract_cno,
    loan_contract_name: '借款合同',
    loan_contract_no: entrustContract.loan_contract_no,
    ensure_contract_name: '保证合同',
    ensure_contract_no: entrustContract.ensure_contract_no,
    customer_name: related.customer_name,
    apply_funds: entrustContract.reply_funds,
    apply_funds_capital: nzhToMoney(Math.round(entrustContract.reply_funds * 10000)),
    load_years: entrustContract.load_years * 12,
    sign_date: dateFormat(new Date(), 'yyyy年MM月dd日'),
    cert_no: isPerson ? related.lender_idcard : related.register_no,
  }

  return addData(SERVICE_NAME, noticeTableName, data)
}

/**
 * 获取流程状态
 * @param {{
 *  approval: object; // 审批表数据
 *  related: object; // 关联表数据
 *  authPerson: object; // 有权审批人
 * }} param 判断流程状态需要用到的数据
 */
export const getProcess = ({ approval, authPerson, user, org }) => {
  const status = [+approval.res_a_status, +approval.res_corp_status]
  return [
    {
      type: 1,
      status: '=1,=0',
      role: {
        user: {
          orgRegionLever: [2, 3],
          userId: authPerson.userId,
        },
      },
      editable: false,
      signLabel: '有权审批人',
      signLevel: 2,
      signName: [{ label: '签字', key: 'res_corp_person' }],
      keys: {
        name: 'res_corp_person',
        status: 'res_corp_status',
        date: 'res_corp_date',
        comment: 'res_corp_option',
      },
      validators: {
        comment: [{ required: true, message: '请输入有权审批人意见' }],
      },
      // afterSave: () => Promise.all([
      //   // updateRelatedLoanStatus(related.customer_related_id, 1),
      // ])
    },
  ].map(it => ({
    ...it,
    editable: calcRole(it.role, { user, org }) && calcStatus(status, it.status),
  }))
}

export const getProcessEditable = (needData, { user, org }) => {
  return getProcess(needData, { user, org }).some(it => it.editable)
}

/**
 * 更新审批内容
 * @param {*} approvalId 审批ID
 * @param {*} bps busProcess
 * @param {*} param2 need data
 */
export const approvalComment = (
  approvalId,
  bps,
  { name, status, approval, solidApproval, otherData, queryId }
) => {
  const date = dateFormat(new Date())
  const afters = []
  let data = {}
  for (const bp of bps) {
    const { keys, beforeSave, afterSave } = bp
    const comment = approval[keys.comment]
    const solidComment = solidApproval[keys.comment]

    // 一人多种权限时，如没有更改意见内容则不用修改对应角色的信息
    if (solidComment && comment === solidComment) {
      continue
    }

    data[keys.name] = name
    data[keys.comment] = comment
    data[keys.date] = date
    data[keys.status] = status
    data.customer_related_id = queryId
    if (beforeSave) {
      data = beforeSave(data)
    }

    if (afterSave && typeof afterSave === 'function') {
      afters.push(afterSave)
    }
  }
  return updateApproval(approvalId, { ...otherData, ...data }).then(res => {
    if (afters.length) {
      return Promise.all(afters.map(it => it()))
    }
    return res
  })
}
